unit mainform;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, cyPanel, Forms, Controls, Graphics,
  Dialogs, ComCtrls, ExtCtrls, Menus, nkTitleBar, nkResizer, LCLIntf,
  VirtualTrees, rxctrls, BCLabel, gogopluginss, rccmd, filesform, welcomeform;

type

  { TfrmMain }

  TfrmMain = class(TForm)
    BCLabel1: TBCLabel;
    CyPanel1: TCyPanel;
    ImageList1: TImageList;
    ImageList2: TImageList;
    ListRemotes: TListView;
    MenuItem1: TMenuItem;
    MenuItem2: TMenuItem;
    MenuItem3: TMenuItem;
    MenuItem4: TMenuItem;
    MenuItem5: TMenuItem;
    nkResizer2: TnkResizer;
    nkTitleBar2: TnkTitleBar;
    Tabs: TPageControl;
    Panel1: TPanel;
    PopAddRemote: TPopupMenu;
    RxSpeedButton1: TRxSpeedButton;
    RxSpeedButton2: TRxSpeedButton;
    RxSpeedButton3: TRxSpeedButton;
    Splitter1: TSplitter;
    StatusBar: TCyPanel;
    StatusBar1: TCyPanel;
    ToolAddNode: TToolButton;
    ToolAddRemote: TToolButton;
    ToolAddUSer: TToolButton;
    ToolAddUsers: TToolButton;
    ToolBar1: TToolBar;
    ToolButton1: TToolButton;
    ToolButton2: TToolButton;
    ToolButton3: TToolButton;
    ToolButton4: TToolButton;
    ToolButton5: TToolButton;
    ToolButton6: TToolButton;
    ToolButton7: TToolButton;
    ToolDeleteNode: TToolButton;
    ToolDeleteRemote: TToolButton;
    ToolDeleteUser: TToolButton;
    ToolEditNode: TToolButton;
    ToolEditRemote: TToolButton;
    ToolEditUser: TToolButton;
    ToolHelp: TToolButton;
    ToolNodeLicense: TToolButton;
    ToolStartNode: TToolButton;
    ToolStopNode: TToolButton;
    procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
    procedure FormShow(Sender: TObject);
    procedure ListRemotesDblClick(Sender: TObject);
    procedure ListRemotesSelectItem(Sender: TObject; Item: TListItem;
      Selected: Boolean);
    procedure RxSpeedButton1Click(Sender: TObject);
    procedure RxSpeedButton2Click(Sender: TObject);
    procedure RxSpeedButton3Click(Sender: TObject);
    procedure ToolButton6Click(Sender: TObject);
    procedure ToolDeleteNodeClick(Sender: TObject);
    procedure ToolEditNodeClick(Sender: TObject);
    procedure ToolHelpClick(Sender: TObject);
  private
    WinMax : boolean;
    OldLeft,OldTop,OldWidth,OldHeight:integer;

  public
    procedure InitDB;
    procedure InitPlugins;
    procedure InitPopAddRemote;
    procedure PopAddRemoteClick(Sender: TObject);
    procedure ReloadListRemotes;
    procedure ClearTab;
    procedure AddFilesTab(AAlias:string; ACaption:string);
    procedure AddWelcomeTab;
    function  IndexOfFilesTab(AAlias:string):integer;
    procedure CreateRemote(ARtype:string;AID:integer);
    procedure CloseFilesTab(AALias:string);

  end;

var
  frmMain: TfrmMain;

implementation

uses
  datamodule, progressform;
{$R *.frm}

{ TfrmMain }

procedure TfrmMain.ClearTab;
begin
  if Assigned(Tabs.ActivePage) then
  begin
    Tabs.ActivePage.Free;
  end;
end;

procedure TfrmMain.AddFilesTab(AAlias: string; ACaption:string);
Var
  TabSheet: TFilesPanel;
  mIndex:integer;
begin
  mIndex:=IndexOfFilesTab(AAlias);
  if  mIndex = -1 then
  begin
    //ClearTab; TODO:改成查询是否存在相同Alias
    TabSheet := TFilesPanel.Create(Tabs);
    TabSheet.Parent := Tabs;
    TabSheet.RAlias:=AALias;
    TabSheet.RootPath:='';
    TabSheet.Caption:=ACaption;
    Tabsheet.ShowForm;
    Tabs.ActivePageIndex := TabSheet.PageIndex;
  end
  else
  begin
    Tabs.ActivePageIndex:=mIndex;
  end;
end;

procedure TfrmMain.AddWelcomeTab;
Var
  TabSheet: TWelcomePanel;
  mIndex:integer;
  i:integer;
begin
  //循环查找欢迎页
  mIndex:=-1;
  for i:=0 to Tabs.PageCount-1 do
  begin
    if Tabs.Pages[i] is TWelcomePanel then
    begin
      mIndex:=i;
      Break;
    end;
  end;
  if  mIndex = -1 then
  begin
    //ClearTab; TODO:改成查询是否存在相同Alias
    TabSheet := TWelcomePanel.Create(Tabs);
    TabSheet.Parent := Tabs;
    TabSheet.Caption:='欢迎';
    Tabsheet.ShowForm;
    Tabs.ActivePageIndex := TabSheet.PageIndex;
  end
  else
  begin
    Tabs.ActivePageIndex:=mIndex;
  end;
end;

function TfrmMain.IndexOfFilesTab(AAlias: string): integer;
var
  i:integer;
begin
  Result:=-1;
  for i:=0 to Tabs.PageCount-1 do
  begin
    if Tabs.Pages[i] is TFilesPanel then
    begin
      if Trim((Tabs.Pages[i] as TFilesPanel).RAlias)=Trim(AAlias) then
      begin
        Result:=i;
        Break;
      end;
    end;
  end;
end;

procedure TfrmMain.CreateRemote(ARtype: string; AID: integer);
var
  i:integer;
  mPlugin:TGoGoPluginItem;
  mProgress:TfrmProgress;
  m:string;
begin
  mProgress:=TfrmProgress.Create(nil);
  mProgress.SetInfo('正在创建对象……');
  mProgress.Show;
  Application.ProcessMessages;
  for i:=0 to Dm.Plugins.Count-1 do
  begin
    if Dm.Plugins.Item(i).LibType = ARtype then
    begin
      mPlugin := Dm.Plugins.Item(i);
      m:=mPlugin.CreateRemote(AID,Dm.conn);
      //showMessage(m);
    end;
  end;
  mProgress.Free;
  mProgress:=nil;
end;

procedure TfrmMain.CloseFilesTab(AALias: string);
var
  i:integer;
begin
  for i:=0 to Tabs.PageCount-1 do
  begin
    if Tabs.Pages[i] is TFilesPanel then
    begin
      if (Tabs.Pages[i] as TFilesPanel).RAlias=AAlias then
      begin
        (Tabs.Pages[i] as TFilesPanel).Free;
        Break;
      end;
    end;
  end;
end;

procedure TfrmMain.RxSpeedButton1Click(Sender: TObject);
begin
  Hide;
  Dm.Plugins.Clear;
  //Dm.Plugins.Free;
  Application.Terminate;
end;

procedure TfrmMain.FormShow(Sender: TObject);
begin
  InitDB;
  InitPlugins;
  InitPopAddRemote;
  RxSpeedButton2Click(nil);
  ReloadListRemotes;
  AddWelcomeTab;
end;

procedure TfrmMain.ListRemotesDblClick(Sender: TObject);
var
  mRemote:string;
  mRtype:string;
  mRid:string;
  mCaption:string;
  mProgress:TfrmProgress;
begin
  //打开指定存储
  if ListRemotes.Selected=nil then
  begin
    MessageDlg('请先选择要打开的网盘。',mtWarning,[mbOK],0);
    Exit;
  end;
  mProgress:=TfrmProgress.Create(nil);
  mProgress.SetInfo('正在打开……');
  mProgress.Show;
  Application.ProcessMessages;
  //获取remote的Alias和Type
  mCaption := ListRemotes.Selected.SubItems.Strings[0];
  mRid := ListRemotes.Selected.SubItems.Strings[3];
  mRemote := ListRemotes.Selected.SubItems.Strings[4];
  mRType := ListRemotes.Selected.SubItems.Strings[5];
  //检查remote是否存在，不存在则创建
  if RemoteExists(mRemote)=False then
  begin
    //创建remote
    CreateRemote(mRType,strtoint(mRid));
  end;
  //打开文件面板
  Self.AddFilesTab(mRemote,mCaption);
  mProgress.Close;
  mProgress.Free;
  mProgress:=nil;
end;

procedure TfrmMain.ListRemotesSelectItem(Sender: TObject; Item: TListItem;
  Selected: Boolean);
begin
  ToolEditNode.Enabled:=Selected;
  ToolDeleteNode.Enabled:=Selected;
end;

procedure TfrmMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
  //删除临时文件夹中所有文件
  ClearTempFiles;
end;

procedure TfrmMain.RxSpeedButton2Click(Sender: TObject);
begin
  if WinMax = False then
  begin
    OldLeft := Self.Left;
    OldTop  := Self.Top;
    OldWidth := Self.Width;
    OldHeight := Self.Height;
    Self.Top:=Self.Monitor.WorkareaRect.Top;
    Self.Left:=Self.Monitor.WorkareaRect.Left;
    Self.Width:=Self.Monitor.WorkareaRect.Width;
    Self.Height:=Self.Monitor.WorkareaRect.Height;
    WinMax := True;
  end
  else
  begin
    Self.Top:=OldTop;
    Self.Left:=OldLeft;
    Self.Width:=OldWidth;
    Self.Height:=OldHeight;
    WinMax := False;
  end;
end;

procedure TfrmMain.RxSpeedButton3Click(Sender: TObject);
begin
  Application.Minimize;
end;

procedure TfrmMain.ToolButton6Click(Sender: TObject);
begin
  Self.AddFilesTab('webdav_1','demo1');
end;

procedure TfrmMain.ToolDeleteNodeClick(Sender: TObject);
var
  mAlias,mID:string;
begin
  //删除
  if ListRemotes.Selected=nil then
  begin
    MessageDlg('请选择要删除的项。',mtWarning,[mbOK],0);
    Exit;
  end;
  if MessageDlg('确认要删除吗？',mtConfirmation,[mbYes,mbNo],0)<>mrYes then
    Exit;
  //获取alias、id，
  mID := ListRemotes.Selected.SubItems.Strings[3];
  mAlias := ListRemotes.Selected.SubItems.Strings[4];
  //关闭窗口
  CloseFilesTab(mAlias);
  //先删除remote实例
  DoConfigDeleteRemote(mAlias);
  //删除数据库记录
  with Dm.InnerQry do
  begin
    Close;
    Sql.Clear;
    Sql.Add('delete from remotes2 where id=:id');
    Params.ParamByName('id').AsInteger:=strtoint(mID);
    ExecSQL;
  end;
  ReloadListRemotes;
end;

procedure TfrmMain.ToolEditNodeClick(Sender: TObject);
var
  mID:string;
  mRType:string;
  mIndex:integer;
  i:integer;
  mResult:string;
begin
  //编辑
  if ListRemotes.Selected<>nil then
  begin
    mID := ListRemotes.Selected.SubItems.Strings[3];
    mRType := ListRemotes.Selected.SubItems.Strings[5];
    mIndex:=-1;
    for i:=0 to Dm.Plugins.Count-1 do
    begin
      if Dm.Plugins.Item(i).LibType = mRtype then
      begin
        mIndex:=i;
        Break;
      end;
    end;
    if mIndex<>-1 then
    begin
      mResult:=dm.Plugins.Item(mIndex).Edit(Self.Handle,Dm.conn, strtoint(mID));
      if mResult='OK' then
      begin
        //窗口返回mrOK，刷新目录列表
        ReloadListRemotes;
      end;
    end;
  end
  else
  begin
    MessageDlg('请选择要编辑的项目。',mtWarning,[mbOK],0);
  end;

end;

procedure TfrmMain.ToolHelpClick(Sender: TObject);
begin
  OpenDocument('http://www.ggyun.top');
end;

//var
//  mPlugin:TGoGoPluginItem;
//  m:string;
//begin
//  //测试plugin
//  mPlugin:=TGoGoPluginItem.Create(Self,ExtractFilepath(Application.ExeName)+'\plugin\webdav.dll');
//// -----------------------------
////  m:=mPlugin.PlugInfo();
////  ShowMessage('Plugin.PlugInfo 说: '+#10#13+#10#13+m);
////  mPlugin.Free;
////  mPlugin:=nil;
//// -----------------------------
////  m:=mPlugin.Edit(Self.Handle,Dm.conn);
//  //showmessage(m);
//  //窗口自释放，无需mPlugin.Free;
//  // -----------------------------
//  m:=mPlugIn.CreateRemote(1,Dm.conn);
//  ShowMessage(m);
//
//end;

procedure TfrmMain.InitDB;
begin
  dm.conn.LibraryLocation:=ExtractFilepath(Application.ExeName)+'\data\sqlite3.dll';
  dm.conn.Database:=ExtractFilepath(Application.ExeName)+'\data\config.db';
  dm.conn.Connect;
end;

procedure TfrmMain.InitPlugins;
var
  mFiles:TStrings;
  i:integer;
  mItem:TGoGoPluginItem;
  mInfo:string;
  m:string;
begin
  dm.Plugins:=TGoGoPlugins.Create(Self);
  //查找plugin目录下的插件Dll
  mFiles := FindAllFiles(ExtractFilepath(Application.ExeName)+'plugin', '*.dll', False);
  for i:=0 to mFiles.Count-1 do
  begin
    mItem:=TGoGoPluginItem.Create(Self,Trim(mFiles.Strings[i]));
    m:=mItem.PlugType();
    mInfo := m;
    mItem.LibType:=mInfo;
    Dm.Plugins.Add(mItem);
  end;
  mFiles.Free;
  //测试
  //if Dm.Plugins.Count>0 then
  //begin
  //  ShowMessage(Dm.Plugins.Item(0).LibType);
  //end;
end;

procedure TfrmMain.InitPopAddRemote;
var
  i:integer;
  mItem:TMenuItem;
begin
  PopAddRemote.Items.Clear;
  for i:=0 to Dm.Plugins.Count-1 do
  begin
    mItem:=TMenuItem.Create(PopAddRemote);
    mItem.Caption:='添加 '+UpperCase(Dm.Plugins.Item(i).LibType)+' 存储';
    mItem.Tag:=i;
    mItem.OnClick:=@PopAddRemoteClick;
    PopAddRemote.Items.Add(mItem);
  end;
end;

procedure TfrmMain.PopAddRemoteClick(Sender: TObject);
var
  mIndex:integer;
  mResult:string;
begin
  mIndex:=(Sender as TMenuItem).Tag;
  mResult:=dm.Plugins.Item(mIndex).Edit(Self.Handle,Dm.conn);
  if mResult='OK' then
  begin
    //窗口返回mrOK，刷新目录列表
    ReloadListRemotes;
  end;
end;

procedure TfrmMain.ReloadListRemotes;
begin
  ListRemotes.Items.BeginUpdate;
  ListRemotes.Items.Clear;
  with dm.InnerQry do
  begin
    Close;
    Sql.Clear;
    Sql.Add('select * from remotes2 order by rname asc');
    Open;
    First;
    while not Eof do
    begin
      with ListRemotes.Items.Add do
      begin
        Caption:='';//FieldByName('rtype').AsString;
        SubItems.Add(FieldByName('rname').AsString);
        //if Trim(FieldByName('rletter').AsString)='' then
        //  SubItems.Add('-')
        //else
        //  SubItems.Add(FieldByName('rletter').AsString);
        SubItems.Add(UpperCase(FieldByName('rtype').AsString));
        SubItems.Add(FieldByName('rcomment').AsString);
        SubItems.Add(inttostr(FieldByName('id').AsInteger));
        SubItems.Add(FieldByName('ralias').AsString);
        SubItems.Add(FieldByName('rtype').AsString);

        ImageIndex:=0;
      end;
      Next;
    end;
  end;
  listRemotes.Items.EndUpdate;
end;

end.

